"use client";
import { listQuestionVoByPageUsingPost } from "@/api/questionController";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import React, { useRef, useState } from "react";
import TagList from "@/components/TagList";
import { TablePaginationConfig, Select, Tag, Input, Button, Space } from "antd";
import Link from "next/link";
import "./index.css";

// 默认标签选项
const DEFAULT_TAG_OPTIONS = [
    "JavaScript",
    "React",
    "Vue",
    "Angular",
    "Node.js",
    "TypeScript",
    "HTML",
    "CSS",
    "算法",
    "数据结构",
    "数据库",
    "网络",
    "安全",
    "性能优化",
    "前端工程化",
].map((tag) => ({ value: tag, label: tag }));

interface Props {
    // 默认值（用于展示服务端渲染的数据）
    defaultQuestionList?: API.QuestionVO[];
    defaultTotal?: number;
    // 默认搜索条件
    defaultSearchParams?: API.QuestionQueryRequest;
}

/**
 * 题目表格组件
 *
 * @constructor
 */
const QuestionTable: React.FC = (props: Props) => {
    const { defaultQuestionList, defaultTotal, defaultSearchParams = {} } = props;
    const actionRef = useRef<ActionType>();
    // 题目列表
    const [questionList, setQuestionList] = useState<API.QuestionVO[]>(
        defaultQuestionList || [],
    );
    // 题目总数
    const [total, setTotal] = useState<number>(defaultTotal || 0);
    // 用于判断是否首次加载
    const [init, setInit] = useState<boolean>(true);

    /**
     * 表格列配置
     */
    const columns: ProColumns<API.QuestionVO>[] = [
        {
            title: "标题",
            dataIndex: "title",
            valueType: "text",
            render: (_, record) => {
                return (
                    <Link href={`/question/${record.id}`} className="question-title-link">
                        {record.title}
                    </Link>
                );
            },
        },
        {
            title: "标签",
            dataIndex: "tagList",
            valueType: "select",
            fieldProps: {
                mode: "tags",
                options: DEFAULT_TAG_OPTIONS,
                placeholder: "选择或输入标签", maxTagCount: 3,
                suffixIcon: null,
                allowClear: true,
                style: { minWidth: 200 },
            },
            renderFormItem: (_, { fieldProps }) => {
                return (
                    <Select
                        {...fieldProps}
                        options={DEFAULT_TAG_OPTIONS}
                        mode="tags"
                        placeholder="选择或输入标签"
                        maxTagCount={3}
                        allowClear
                    />
                );
            },
            render: (_, record) => {
                return <TagList tagList={record.tagList} />;
            },
        },
    ];



    return (
        <div className="question-table">
            <ProTable<API.QuestionVO>
                actionRef={actionRef}
                size="large"
                search={{
                    labelWidth: "auto",
                    optionRender: (searchConfig, formProps, dom) => [...dom],
                }}
                form={{
                    initialValues: defaultSearchParams,
                }}
                dataSource={questionList}
                pagination={
                    {
                        defaultPageSize: 10,
                        showTotal: (total) => `共 ${total} 条题目`,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: ['10', '20'],
                        total,
                    } as TablePaginationConfig
                }
                request={async (params, sort, filter) => {
                    // 首次请求
                    if (init) {
                        setInit(false);
                        // 如果已有外层传来的默认数据，无需再次查询
                        if (defaultQuestionList && defaultTotal) {
                            return;
                        }
                    }

                    const sortField = Object.keys(sort)?.[0] || "createTime";
                    const sortOrder = sort?.[sortField] || "descend";

                    // 处理标签搜索参数
                    const { tagList, ...otherParams } = params;
                    const requestParams: API.QuestionQueryRequest = {
                        ...otherParams,
                        sortField,
                        sortOrder,
                        ...filter,
                    };

                    // 如果选择了标签，将tagList转换为tags参数
                    if (tagList && tagList.length > 0) {
                        requestParams.tags = tagList;
                    }

                    const { data, code } =
                        await listQuestionVoByPageUsingPost(requestParams);

                    // 更新结果
                    const newData = data?.records || [];
                    const newTotal = data?.total || 0;
                    // 更新状态
                    setQuestionList(newData);
                    setTotal(newTotal);

                    return {
                        success: code === 0,
                        data: newData,
                        total: newTotal,
                    };
                }}
                columns={columns}
                options={{
                    density: false,
                    fullScreen: false,
                    reload: true,
                    setting: true,
                }}
                rowClassName={() => "question-table-row"}
            />
        </div>
    );
};
export default QuestionTable;